#!/bin/bash
# autobackux - Backup your files
# Jon Peeters - June 2011
 
# autobackux is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
call () {
	if [ $# -lt 1 ]; then
		return # Nothing to do 
	fi
	fct=$1
	shift
	type "$fct" 1>/dev/null 2>/dev/null
	if [ $? -ne 0 ]; then # Function doesn't exits. Must be loaded
		f=$(egrep -l "$fct ?\(\)" src/*)
		if [[ -z "$f" ]]; then
			fatal_error "Error : function \"$fct\" doesn't exist!"
		fi
		source $f
		if [ $? -ne 0 ]; then
			fatal_error "Error : cannot load file $f"
		fi		
	fi
	$fct "$@"
}

display_error() {
	echo "[WARNING] "$(date "+%d-%m-%y %H:%M.%S")" - $1" >> "$errors_log"
	zenity --warning --text="$1"
}

fatal_error() {
	echo "[ERROR] "$(date "+%d-%m-%y %H:%M.%S")" - $1" >> "$errors_log"
	zenity --error --text="$1"
	exit 1
}
 
check_for_dependencies() {
	clear
	error=1
	deps=( "zenity" "rsync" )
	for d in ${deps[@]}; do
		if [[ "$(whereis $d)" == "$d:" ]]; then
			echo -e "ERROR : $d is missing!\nDebian, Ubuntu and Mint users can type (in a terminal) :\n\n sudo apt-get install $d"
			read
			error=0
		fi
	done
	if [[ "$error" -eq 0 ]]; then
		exit
	fi
}

check_for_updates() {
	if [[ -f "../updatux.sh" ]]; then
		../updatux.sh "$PWD"
	fi
}

#************************** Main **************************

clear
check_for_dependencies
check_for_updates
echo -e "Starting autobackux...\n"

errors_log="errors.log"
call initialize
call main_menu

echo -e "End of autobackux...\n"
sleep 2
exit 0


